package com.example.summary.sort;

import com.alibaba.fastjson.JSON;

/**
 * Created by wzn on 2019/1/7.
 */
public class GuiBin {

    public static void main(String[] args) {
        int[] x = {14, 23, 16, 15, 11};
        sort2(x, 0, x.length - 1);
        System.out.println(JSON.toJSONString(x));
    }


    public static int[] sort(int[] a, int low, int high) {

        int mid = (low + high) / 2;
        if (low < high) {
            sort(a, low, mid);
            sort(a, mid + 1, high);
            //左右归并
            merge(a, low, mid, high);
        }
        return a;
    }

    public static void merge(int[] a, int low, int mid, int high) {
        int[] temp = new int[high - low + 1];
        int i = low;
        int j = mid + 1;
        int k = 0;
        // 把较小的数先移到新数组中
        while (i <= mid && j <= high) {
            if (a[i] < a[j]) {
                temp[k++] = a[i++];
            } else {
                temp[k++] = a[j++];
            }
        }
        // 把左边剩余的数移入数组
        while (i <= mid) {
            temp[k++] = a[i++];
        }
        // 把右边边剩余的数移入数组
        while (j <= high) {
            temp[k++] = a[j++];
        }
        // 把新数组中的数覆盖nums数组
        for (int x = 0; x < temp.length; x++) {
            a[x + low] = temp[x];
        }
    }


    public static void sort2(int[] nums, int begin, int end) {

        if (end > begin) {
            int mid = (end + begin) / 2;

            sort2(nums, begin, mid);
            sort2(nums, mid + 1, end);

            merge2(nums, begin, mid, end);
        }


    }

    public static void merge2(int[] merge, int begin, int mid, int end) {
        int[] newMerge = new int[end - begin + 1];
        int x = begin;
        int y = mid + 1;
        int z = 0;

        while (x <= mid && y <= end) {
            if (merge[x] <= merge[y]) {
                newMerge[z++] = merge[x++];
            }

            if (merge[x] > merge[y]) {
                newMerge[z++] = merge[y++];
            }
        }

        while (x <= mid) {
            newMerge[z++] = merge[x++];
        }

        while (y <= end) {
            newMerge[z++] = merge[y++];
        }

        for (int i = 0; i < newMerge.length; i++) {
            merge[begin++] = newMerge[i];
        }
    }
}
